<template>
	<div class="index-filters" v-if="showFilter">
		<!-- 视图切换 -->
		<div class="index-filters-sort flex">
			<div>
				<a-select v-if="toggleView" size="mini" v-model="viewType" :style="{ width: '130px' }" @change="handleBtn('viewType', $event)">
					<a-option v-for="item in viewList" :key="item.value" :value="item.value" :label="item.label" />
				</a-select>
			</div>
			<div class="right">
				<a-trigger :trigger="['click']" position="br" :popup-translate="[0, 5]">
					<div class="flex"> <i class="EachApp EachApp_paixu"></i>排序 </div>
					<template #content>
						<div class="trigger-style sort-list flex">
							<a-radio-group v-model="filterParams.sort" @change="handleBtn('sort', $event)" class="flex m50">
								<a-radio v-for="item in SORT_TYPE" :key="item.value" :value="item.value">{{ item.label }}</a-radio>
							</a-radio-group>
						</div>
					</template>
				</a-trigger>
				<a-trigger :trigger="['click']" position="br" :popup-translate="[0, 5]">
					<div class="flex"> <i class="EachApp EachApp_paixu"></i>更多</div>
					<template #content>
						<div class="trigger-style sort-list flex">
							<div class="item" v-for="item in btnList" :key="item.value">
								<a-button>{{ item.label }}</a-button>
							</div>
						</div>
					</template>
				</a-trigger>
			</div>
		</div>
		<!-- 搜索条件 -->
		<div :class="['index-filters-item flex', { height: !filterList.length && !isCtrlK }]" :style="{ '--filter-height': geiHeight }">
			<div class="tag-box" ref="el">
				<a-tag v-for="(item, index) in filterList" :key="index" color="arcoblue">
					<template v-if="isValid(item.fieldShow)">
						<span>{{ `${item.label}: ${item.fieldShow}` }}</span>
					</template>
					<template v-else>
						<span v-if="item.options">{{ `${item.label}: ${item.options.find((child) => child.value === item.value)?.label}` }}</span>
						<span v-else>
							<template v-if="inputTag.includes(item.type) || !item.type">{{ `${item.label}: ${item.value}` }}</template>
							<template v-if="item.type === 'select'">{{ item.label }}: {{ item.selectList.find((child) => child.id === item.value)?.label }}</template>
						</span>
					</template>
					<i class="EachApp EachApp_guanbi close" @click="handleDelete(item.filterIndex, index, item.keys, item)"></i>
				</a-tag>
			</div>
			<div class="right flex" ref="buttonEl">
				<com-trigger position="bottom">
					<a-button type="text" link size="small" ref="popoverBtnRef" v-click-outside="handleMixinPopover">添加过滤</a-button>
					<template #content>
						<slot> </slot>
					</template>
				</com-trigger>
				<a-button type="text" @click="handleBtn('reset')" class="hover info">重置</a-button>
				<a-button type="primary" size="small" @click="handleBtn('save')">保存新视图</a-button>
			</div>
		</div>
	</div>
</template>
<script lang="ts" setup>
const popoverBtnRef = ref();
import { useUserStore } from "@/store/modules/user";
import { useCache } from "@/hooks/useCache";
import mitt from "@/utils/bus";
import mixin from "@/mixins/index";
import { SORT_TYPE } from "@/utils/filter";
import { useElementSize } from "@vueuse/core";
import { isValid } from "@/utils/index";

const el = ref(null);
const buttonEl = ref(null);
const { height } = useElementSize(el);
const { height: buttonHeight } = useElementSize(buttonEl);
const inputTag = ["input", "text", "number", "price"];
const geiHeight = computed(() => {
	const childHeight = height.value < buttonHeight.value ? buttonHeight.value : height.value; //标签高度比按钮高度低就用按钮的高度
	const padding = 4 * 2;
	const border = 1;
	return childHeight + padding + border + "px";
});
defineProps({
	toggleView: {
		type: Boolean,
		default: true
	},
	showFilter: {
		type: Boolean,
		default: true
	}
});
const emit = defineEmits(["update"]);
const { wsCache } = useCache();
const userStore = useUserStore();
const { handleMixinPopover } = mixin();
const getEmit = inject("getEmit");
const getList = inject("getList");

const route = useRoute();

const viewType = ref(0);
const viewList = ref([
	{ value: 0, label: "阶段视图" },
	{ value: 1, label: "表格视图" }
]);
const btnList = ref([
	{ value: 0, label: "按钮" },
	{ value: 1, label: "按钮" },
	{ value: 2, label: "按钮" }
]);
const filterList = ref([]); // 过滤参数列表
const filterParams = ref({
	sort: 0
}); // 过滤参数信息
const filterParamsInit = ref({ ...filterParams.value });
const searchKey = ref(null); // 关键字搜索参数
const isCtrlK = ref(false);
mitt.on("Ctrl_K", () => {
	isCtrlK.value = !isCtrlK.value;
});
watch(
	() => filterList.value,
	async (e) => {
		filterParams.value = {
			...filterParamsInit.value,
			...e.reduce((pre, current) => {
				pre[current?.keys] = current?.value;
				return pre;
			}, {})
		};
	},
	{ deep: true, immediate: true }
);

onMounted(() => {
	const list = wsCache.get("viewInfo");
	const items = list?.find((item) => item.page === route.path);
	if (list && items) {
		viewType.value = items.viewType;
		filterList.value = items.filterList;
		mitt.emit("handleEmit", { emitType: "view", value: items.viewType });
		const searchKeyParams = items.filterList.find((item) => item.filterIndex === 0);
		searchKey.value = { ...searchKeyParams };
		mitt.emit("handleDelete", searchKeyParams.value);
		if (items?.filterList.length) {
			FormFilterRef.value.filterList.map((item) => {
				items?.filterList.forEach((child) => {
					if (item.filterIndex === child.filterIndex) {
						Object.keys(item).forEach((keys) => {
							item[keys] = child[keys];
						});
					}
				});
				return item;
			});
		}
	}
});

// 搜索-关键字
const handleSearchKeys = (value, index) => {
	if (!value) {
		const idx = filterList.value.findIndex((item) => item.filterIndex === index);
		filterList.value.splice(idx, 1);
	} else {
		searchKey.value = { filterIndex: 0, label: "模糊筛选", keys: "searchKey", value, filterType: "keywords" };
		const idx = filterList.value.findIndex((item) => item.filterIndex === 0);
		if (idx !== -1) {
			filterList.value.splice(idx, 1, searchKey.value);
		} else {
			filterList.value.push(searchKey.value);
		}
	}
};
// 搜索-添加过滤提交的参数
const handleSubmitFilter = (value) => {
	if (value === "reset") {
		filterList.value = [];
		mitt.emit("handleDelete", "");
		nextTick(() => {
			getList();
		});
	} else {
		const list = JSON.parse(JSON.stringify(value));
		console.log(list);

		list.forEach((item) => {
			const isIndex = filterList.value.findIndex((child) => child.filterIndex === item.filterIndex);
			console.log(isIndex, "isIndex");

			if (isIndex === -1) {
				if (isValid(item.value)) {
					filterList.value.push(item);
				}
			} else {
				if (isValid(item.value)) {
					filterList.value.splice(isIndex, 1, item);
				} else {
					filterList.value.splice(isIndex, 1);
				}
				// filterList.value.splice(isIndex, 1,item);
			}
		});
	}
};

// 清除关键字
const handleDelete = async (filterIndex, index, keys, item) => {
	filterParams.value[keys] = "";
	if (isValid(item.fieldShow)) {
		mitt.emit("delField", filterIndex);
	}
	getEmit({ emitType: "delete", value: filterList.value.length === 1 });
	filterList.value.splice(index, 1);
	emit('update',filterList.value)
};
// 按钮处理
const handleBtn = async (type, value) => {
	// viewType切换视图   save保存新视图   reset重置
	if (type === "viewType") {
		getEmit({ emitType: "view", value });
	} else if (type === "save") {
		userStore.setViewInfo({
			page: route.path,
			viewType: viewType.value,
			filterList: JSON.parse(JSON.stringify(filterList.value))
		});
	} else if (type === "reset") {
		// 重置
		filterList.value = [];
		searchKey.value = null;
		mitt.emit("handleDelete", "");
		nextTick(() => {
			getList();
		});
	} else if (type === "sort") {
		// 排序
		getList();
	}
};
// 关键字搜索
mitt.on("handleSearch", (value) => {
	handleSearchKeys(value);
	emit('update',filterList.value)
});
// 添加字段筛选
mitt.on("fieldFilter", (value) => {
	handleSubmitFilter(value);
	emit('update',filterList.value)
});

watch(()=>route,()=>{
	filterList.value = []
	isCtrlK.value = false
},{deep:true})
defineExpose({
	filterParams,
	filterList,
	handleSubmitFilter
});
</script>
<style scoped lang="scss"></style>
